package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.thread.AppThreadLocalUtil;
import com.heima.common.Freemarker.FreemarkerGenerator;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.schedule.CacheService;
import com.heima.minio.MinIoTemplate;
import com.heima.model.article.ArticleVisitStreamMess;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private FreemarkerGenerator freemarkerGenerator;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult load(ArticleHomeDto dto) {
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, 1);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult load2(ArticleHomeDto dto) {
        if (dto==null){
            return ResponseResult.okResult("");
        }
        String tag = dto.getTag();
        String s = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + tag);
        if (s==null){
            this.load(dto);
        }
        List<ApArticle> apArticles = JSON.parseArray(s, ApArticle.class);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult loadmore(ArticleHomeDto dto) {
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, 1);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult loadnew(ArticleHomeDto dto) {
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, 2);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public void content(Long articleId) {
        //根据id查询文章详细内容表
        LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleContent::getArticleId,articleId);
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(wrapper);
        //将文章内容转为集合放到map集合里
        HashMap<String, Object> map = new HashMap<>();
        map.put("content", JSON.parseArray(apArticleContent.getContent()));
        //用freemarkerGenerator插件返回字节流
        InputStream is = freemarkerGenerator.generate("article.ftl", map);
        //使用minio插件将字节流上传，返回地址
        String url = minIoTemplate.uploadFile("", articleId + ".html", is, "html");
        //根据id查询出文章信息表
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if (apArticle==null){
            log.error("文章为空");
            return;
        }
        //将返回的url地址覆盖并更新
        apArticle.setStaticUrl(url);
        apArticleMapper.updateById(apArticle);

    }

    @Override
    @Transactional
    public ResponseResult saveArticle(ArticleDto dto) {
        //判空
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Long id = dto.getId();
        String contentDto = dto.getContent();
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
        //判断dto里面是否有id
        if (id==null){
            //id为空走新增逻辑
            //新增article表
            int insertResult = apArticleMapper.insert(apArticle);
            if (insertResult<1){
                return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
            }
            //新增article_config表
            ApArticleConfig config = new ApArticleConfig();
            config.setArticleId(apArticle.getId());
            config.setIsComment(true);
            config.setIsForward(true);
            config.setIsDelete(false);
            config.setIsDown(false);
            int configResult = apArticleConfigMapper.insert(config);
            if (configResult<1){
                throw new RuntimeException("文章插入失败");
            }
            //新增article_content表
            ApArticleContent content = new ApArticleContent();
            content.setArticleId(apArticle.getId());
            content.setContent(contentDto);
            int contentResult = apArticleContentMapper.insert(content);
            if (contentResult<1){
                throw new RuntimeException("文章插入失败");
            }
            //调用方法保存到文章详细表里
            content(apArticle.getId());
            return ResponseResult.okResult(apArticle.getId());
        }else {
            //有id走修改逻辑
            int updateResult = apArticleMapper.updateById(apArticle);
            if (updateResult<1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }
            LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApArticleContent::getArticleId,id);
            ApArticleContent content = new ApArticleContent();
            content.setContent(contentDto);
            int updateByIdResult = apArticleContentMapper.update(content,wrapper);
            if (updateByIdResult<1){
                throw new RuntimeException("文章修改失败");
            }
            //调用方法保存到文章详细表里
            content(id);
            return ResponseResult.okResult(id);
        }


    }

    @Override
    public void addarticle(ApArticle apArticle, String content) {

        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,vo);
        vo.setContent(content);

        kafkaTemplate.send("article.es.sync.topic",JSON.toJSONString(vo));
    }

    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtil.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer id = user.getId();
        if (id==null  || id ==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short type = dto.getType();
        Long entryId = dto.getEntryId();
        Long  currentTimeMillis= System.currentTimeMillis();
        if (type==0){
            Object o = cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + entryId, id.toString());
            if (o==null){
                cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR+entryId,id.toString(),currentTimeMillis.toString());
            }
        }
        cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR+entryId,id.toString());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtil.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer id = user.getId();
        if (id==null  || id ==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Long articleId = dto.getArticleId();
        Integer authorId = dto.getAuthorId();
        Boolean isLike=false,isUnLike=false,isCollection=false,isFollow=false;
        Object o = cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + articleId, id.toString());
        if (o==null){
            isLike=true;
        }
        Object o2 = cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + articleId, id.toString());
        if (o2==null){
            isUnLike=true;
        }
        Object o3 = cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + articleId, id.toString());
        if (o3==null){
            isCollection=true;
        }
        Double aDouble = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + id.toString(), authorId.toString());
        if (aDouble==null){
            isFollow=true;
        }
        HashMap<String, Object> map = new HashMap<>(4);
        map.put("islike",isLike);
        map.put("isunlike",isUnLike);
        map.put("iscollection",isCollection);
        map.put("isfollow",isFollow);
        return ResponseResult.okResult(map);
    }

    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        if (mess==null){
            return;
        }
        Long articleId = mess.getArticleId();
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if (apArticle==null){
            log.warn("文章"+articleId+"为空");
            return;
        }
        apArticle.setLikes(apArticle.getLikes()+mess.getLike());
        apArticle.setViews(apArticle.getViews()+mess.getView());
        apArticle.setComment(apArticle.getComment()+mess.getComment());
        apArticle.setCollection(apArticle.getCollection()+mess.getCollect());
        Integer score = updateAparticle(apArticle);
        Integer channelId = apArticle.getChannelId();
        replaceToRedis(apArticle,score,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+channelId);

        replaceToRedis(apArticle,score,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);

    }
    private void replaceToRedis(ApArticle article, Integer score, String key){
        String cache = cacheService.get(key);
        if (cache==null){
            return;
        }
        List<HotArticleVo> hotArticleVos = JSON.parseArray(cache, HotArticleVo.class);
        if (CollectionUtils.isEmpty(hotArticleVos)){
            return;
        }
        Boolean flag=false;
        for (HotArticleVo hotArticleVo : hotArticleVos) {
            if (hotArticleVo == null) {
                continue;
            }
            Long voId = hotArticleVo.getId();
            Long articleId = article.getId();
            if (voId.equals(articleId)) {
                hotArticleVo.setScore(score);
                flag = true;
                break;
            }
        }
            if (!flag) {
                if (hotArticleVos.size() < 30) {
                    HotArticleVo vo = new HotArticleVo();
                    BeanUtils.copyProperties(article, vo);
                    vo.setScore(score);
                    hotArticleVos.add(vo);
                    hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                }
                } else {
                    HotArticleVo articleVo = hotArticleVos.get(29);
                    if (articleVo.getScore() < score) {
                      hotArticleVos.remove(articleVo);
                      HotArticleVo newVo = new HotArticleVo();
                      BeanUtils.copyProperties(article, newVo);
                      newVo.setScore(score);
                      hotArticleVos.add(newVo);
                }
            }
        hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());

        cacheService.set(key, JSON.toJSONString(hotArticleVos));
    }


    private Integer updateAparticle(ApArticle apArticle){
        HotArticleVo vo = new HotArticleVo();
        BeanUtils.copyProperties(apArticle,vo);
        Integer totle=0;
        if (vo.getViews()!=null){
            totle+=vo.getViews();
        }
        if (vo.getComment()!=null){
            totle+=vo.getComment()*3;
        }
        if (vo.getCollection()!=null){
            totle+=vo.getCollection()*5;
        }
        if (vo.getLikes()!=null){
            totle+=vo.getLikes()*8;
        }
        vo.setScore(totle);

        return vo.getScore();
    }
}
